<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Inmueble extends CI_Controller {

	function __construct()
	{
		parent::__construct();
		$this->load->database();
		$this->load->helper('url');
		$this->load->helper('form');
		$this->load->model('TipoPropiedad','',TRUE);
		$this->load->model('TipoOperacion','',TRUE);
		$this->load->model('Zona','',TRUE);
		$this->load->model('Localidad','',TRUE);
		$this->load->model('Barrio','',TRUE);
		$this->load->model('EstadoPropiedad','',TRUE);
		$this->load->model('Adicional','',TRUE);
		$this->load->model('Servicio','',TRUE);
		$this->load->model('Propiedad','',TRUE);
		$this->load->model('Espacio','',TRUE);
	}
	
	/**
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 * 		http://example.com/index.php/welcome
	 *	- or -  
	 * 		http://example.com/index.php/welcome/index
	 *	- or -
	 * Since this controller is set as the default controller in 
	 * config/routes.php, it's displayed at http://example.com/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/welcome/<method_name>
	 * @see http://codeigniter.com/user_guide/general/urls.html
	 */
	public function index()
	{

		$zonas = $this->Zona->get_paged_list(30, 0)->result();
		$tipospropiedad = $this->TipoPropiedad->get_paged_list(30, 0)->result();
		
		
		// load view
		$data['tipospropiedad'] = $tipospropiedad;
		$data['zonas'] = $zonas;
		$data['propiedades'] = array();
		$barraFiltros = $this->load->view('view_barraFiltros', $data, TRUE);
		$data['barraFiltros'] = $barraFiltros;
		$out = $this->load->view('view_venta_alquiler', $data, TRUE);
		$data['out'] = $out;
		$this->load->view('view_template', $data);
	}
	
	public function demo()
	{
		/*
		$zonas = $this->Zona->get_paged_list(30, 0)->result();
		$tipospropiedad = $this->TipoPropiedad->get_paged_list(30, 0)->result();
		
		
		// load view
		$data['tipospropiedad'] = $tipospropiedad;
		$data['zonas'] = $zonas;
		$data['propiedades'] = array();
		$barraFiltros = $this->load->view('view_barraFiltros', $data, TRUE);
		$data['barraFiltros'] = $barraFiltros;
		$out = $this->load->view('view_demoUpload', $data, TRUE);
		$data['out'] = $out;*/
		$this->load->view('view_demoUpload');
	}
	
	public function getLocalidades()
	{
		$this->load->database();
		$this->load->helper('url');
		$this->load->helper('form');
		$this->load->model('Localidad','',TRUE);
		//$result[] = array();
		$idZona = trim($this->input->post('idZona'));
		$localidades = $this->Localidad->get_by_zona($idZona)->result();
		foreach ($localidades as $val){
		  $result[] = array(
			'id' => $val->idLocalidad,
			'desc' => $val->descripcion,
		  );
		}
		echo json_encode($result);
	}
	
	public function getBarrios()
	{
		$this->load->database();
		$this->load->helper('url');
		$this->load->helper('form');
		$this->load->model('Barrio','',TRUE);

		//$result[] = array();
		$idZona = trim($this->input->post('idZona'));
		$idLocalidad = trim($this->input->post('idLocalidad'));
		$barrios = $this->Barrio->get_by_localidad($idZona,$idLocalidad )->result();
		foreach ($barrios as $val){
		  $result[] = array(
			'id' => $val->idBarrio,
			'desc' => $val->descripcion,
		  );
		}
		echo json_encode($result);
	}
	
	public function getFotos($id)
	{
		$this->load->helper('url');
		$this->load->helper('form');

		$result = $this->Propiedad->get_fotos($id);

		echo json_encode($result);
	}
	
	public function getBarriosLocalidades()
	{
		$this->load->database();
		$this->load->helper('url');
		$this->load->helper('form');
		$this->load->model('Barrio','',TRUE);
		$tipoLugar = '';
		//$result[] = array();
		$idZona = trim($this->input->post('idZona'));
		$idLocalidad = trim($this->input->post('idLocalidad'));
		$barrios = $this->Barrio->get_by_zona($idZona)->result();
		if (count($barrios) == 0){
			$tipoLugar = 'L';
			$barrios = $this->Localidad->get_by_zona($idZona)->result();
		}else{
			$tipoLugar = 'B';
		}
		
		if ($tipoLugar == 'B')
			foreach ($barrios as $val){
			  $result[] = array(
				'id' => $val->idBarrio,
				'desc' => $val->descripcion,
				'tipo' => 'B',
			  );
			}
		else
			foreach ($barrios as $val){
			  $result[] = array(
				'id' => $val->idLocalidad,
				'desc' => $val->descripcion,
				'tipo' => 'L',
			  );
			}
			
		echo json_encode($result);
	}
		
	public function add()
	{

		$estadosPropiedad = $this->EstadoPropiedad->get_paged_list(30, 0)->result();
		$tipooperacion = $this->TipoOperacion->get()->result();
		$tipospropiedad = $this->TipoPropiedad->get_paged_list(30, 0)->result();
		$zonas = $this->Zona->get_paged_list(30, 0)->result();
		$adicionales = $this->Adicional->get_paged_list(30, 0)->result();
		$servicios = $this->Servicio->get_paged_list(30, 0)->result();
		$espacios = $this->Espacio->get_paged_list(100, 0)->result();
		$etiquetas = $this->Propiedad->get_fotosEtiquetas();
		
		$data['propiedad'] = null;
		$data['idPropiedadOriginal'] = null;
		$css_files = $this->cargarCSS();
		$js_files = $this->cargarJS();
		
						
		// load view
		//$data['css_files'] = $css_files;
		$data['tipospropiedad'] = $tipospropiedad;
		$data['tipooperacion'] = $tipooperacion;
		
		$data['estadosPropiedad'] = $estadosPropiedad;
		$data['zonas'] = $zonas;
		$data['adicionales'] = $adicionales;
		$data['servicios'] = $servicios;
		$data['espacios'] = $espacios;
		$data['etiquetas'] = $etiquetas;
		$data['propAdicionales'] = array();
		$data['propServicios'] = array();
		$data['propEspacios'] = array();
		
		$out = $this->load->view('view_propiedadAdd', $data,TRUE);
		//$out = $this->load->view('view_upload', $data,TRUE);
		$data['output'] = $out;
		$data['css_files'] = $css_files;
		$data['js_files'] = $js_files;
		$data['titulo'] = 'Propiedad';
		
		$this->load->view('view_crud', $data);
	}
	
	function _set_fields(){
        $fields['titulo'] = 'titulo';
         
        $this->form_validation->set_fields($fields);
    }
    
	public function deletePropiedad($id){
		$this->Propiedad->copiarPropiedad($id);
		
		$this->deleteFotos($id);
		$this->Propiedad->deleteAdicionales($id);
		$this->Propiedad->deleteServicios($id);
		$this->Propiedad->deleteEspacios($id);
		$this->Propiedad->delete($id);
		redirect('crud/');
	}
	
	public function vistaTest(){
		$this->load->helper('url');
		$this->load->helper('form');
		$this->load->view('view_testing', NULL);
	}
	
	public function save(){
		$id = $this->guardar();
		redirect('inmueble/edit/' . $id);
	}
	
	public function saveAndBack(){
		$this->guardar();
		redirect('crud/');
	}
	
	public function guardar()
	{
		
		$data = $this->cargarData();
		$adicionales = $this->input->post('adicional');
		$servicios = $this->input->post('servicio');
		$espacios = $this->input->post('espacios');
		$espaciosId = $this->input->post('espaciosId');
		
		if ($this->input->post('idPropiedad') == null)
		{
			$id = $this->Propiedad->insert($data);
			if ($this->input->post('idPropiedadOriginal') != null)
			{
				$idPropiedadOriginal = $this->input->post('idPropiedadOriginal');
				$this->copiar_directorio(dirname($_SERVER['SCRIPT_FILENAME']).'/assets/melamud/uploads/'. $idPropiedadOriginal .'/',dirname($_SERVER['SCRIPT_FILENAME']).'/assets/melamud/uploads/'. $id .'/');
			}
		}else
		{
			$id = $this->input->post('idPropiedad');
			$this->Propiedad->update($id,$data);
		}
		
		$this->Propiedad->insertAdicionales($id,$adicionales);
		$this->Propiedad->insertServicios($id,$servicios);
		$this->Propiedad->insertEspacios($id,$espacios,$espaciosId);
		
		return $id;
	}
	
	public function setPortada($idPropiedad)
	{
		$esPortada = 0;
		$propiedad = $this->Propiedad->get_by_id($idPropiedad)->result();
		$propiedad = $propiedad[0];
		if ($propiedad->esPortada==0)
			$esPortada = 1;
		else
			$esPortada =0;

		$data =	$data = array(
				   'esPortada' => $esPortada,
				);
		$this->Propiedad->update($idPropiedad,$data);
	
		redirect('crud/propiedad_management/');
		
	}
	public function edit($id)
	{
		$data = $this->cargarPantalla($id);
		$css_files = $this->cargarCSS();
		$js_files = $this->cargarJS();
		$data['idPropiedadOriginal'] = null;
		
		$out = $this->load->view('view_propiedadAdd', $data,TRUE);
		//$out = $this->load->view('view_upload', $data,TRUE);
		$data['output'] = $out;
		$data['css_files'] = $css_files;
		$data['js_files'] = $js_files;
		$data['titulo'] = 'Propiedad';
		
		$this->load->view('view_crud', $data);

	}
	public function duplicar($id)
	{
		$data = $this->cargarPantalla($id);
		$css_files = $this->cargarCSS();
		$js_files = $this->cargarJS();
		
		$data['idPropiedadOriginal'] = $data['propiedad']->idPropiedad;
		//$data['propiedad']->idPropiedad="";
		
		
		$out = $this->load->view('view_propiedadAdd', $data,TRUE);
		//$out = $this->load->view('view_upload', $data,TRUE);
		$data['output'] = $out;
		$data['css_files'] = $css_files;
		$data['js_files'] = $js_files;
		$data['titulo'] = 'Propiedad';
		
		$this->load->view('view_crud', $data);

	}
	
	public function restaurar($id)
	{
		$this->Propiedad->restaurarPropiedad($id);
		
		$this->Propiedad->deleteAdicionalesDeleted($id);
		$this->Propiedad->deleteServiciosDeleted($id);
		$this->Propiedad->deleteEspaciosDeleted($id);
		$this->Propiedad->deleteDeleted($id);
		redirect('crud/back_propiedad_management');

	}
	public function cargarPantalla($id)
	{
	
		$tipospropiedad = $this->TipoPropiedad->get_paged_list(100, 0)->result();
		$tipooperacion = $this->TipoOperacion->get()->result();
		$zonas = $this->Zona->get_paged_list(100, 0)->result();
		$estadosPropiedad = $this->EstadoPropiedad->get_paged_list(100, 0)->result();
		$adicionales = $this->Adicional->get_paged_list(100, 0)->result();
		$servicios = $this->Servicio->get_paged_list(100, 0)->result();
		$espacios = $this->Espacio->get_paged_list(100, 0)->result();
		$propiedad = $this->Propiedad->get_by_id($id)->result();
		$localidad = $this->Localidad->get_by_id($propiedad[0]->idLocalidad)->result();
		$propAdicionales = $this->Propiedad->get_adicionales_array($id);
		$propServicios = $this->Propiedad->get_servicios_array($id);
		$propEspacios = $this->Propiedad->get_espacios_array($id);
		$etiquetas = $this->Propiedad->get_fotosEtiquetas();
		
		// load view
		//$data['css_files'] = $css_files;
		//$data['fotos'] = $map;
		$data['tipospropiedad'] = $tipospropiedad;
		$data['tipooperacion'] = $tipooperacion;
		
		$data['zonas'] = $zonas;
		$data['estadosPropiedad'] = $estadosPropiedad;
		$data['adicionales'] = $adicionales;
		$data['servicios'] = $servicios;
		$data['espacios'] = $espacios;
		$data['propiedad'] = $propiedad[0];
		$data['localidad'] = $localidad;
		$data['propAdicionales'] = $propAdicionales;
		$data['propServicios'] = $propServicios;
		$data['propEspacios'] = $propEspacios;
		$data['etiquetas'] = $etiquetas;

		return $data;
	}
	
	 public function deleteFotos($idPropiedad)
    {
		$this->load->helper('url');
		$this->load->helper('form');
		$this->borrar_directorio(dirname($_SERVER['SCRIPT_FILENAME']).'/assets/melamud/uploads/'. $idPropiedad .'/',true);
		
	}
	function borrar_directorio($dir, $borrarme)
	{
		if(!$dh = @opendir($dir)) return;
		while (false !== ($obj = readdir($dh))) 
		{
			if($obj=='.' || $obj=='..') continue;
			if (!@unlink($dir.'/'.$obj)) $this->borrar_directorio($dir.'/'.$obj, true);
		}
		closedir($dh);
		if ($borrarme)
		{
			@rmdir($dir);
		}
	}
	 
	function copiar_directorio( $source, $target ) {
		if ( is_dir( $source ) ) {
			@mkdir( $target );
			$d = dir( $source );
			while ( FALSE !== ( $entry = $d->read() ) ) {
				if ( $entry == '.' || $entry == '..' ) {
					continue;
				}
				$Entry = $source . '/' . $entry;
				if ( is_dir( $Entry ) ) {
					$this->copiar_directorio( $Entry, $target . '/' . $entry );
					continue;
				}
				copy( $Entry, $target . '/' . $entry );
			}

			$d->close();
		}else {
			copy( $source, $target );
		}
	}
	 
    public function upload($file=NULL)
    {
        error_reporting(E_ALL | E_STRICT);
		
		$this->load->helper('url');
		$this->load->helper('form');
        $this->load->helper("upload.class");
		
		$referer = explode("/", $_SERVER['HTTP_REFERER']); //$this->input->post('idPropiedad');
		$idPropiedad = $referer[count($referer)-1];
		
		$serv = './assets/melamud/uploads/' ;

		$ruta = $serv . $idPropiedad;
		//echo $ruta;
		//die();
		if(!file_exists($ruta))
		{
			mkdir($ruta);
			mkdir($ruta . '/thumbnails/');
			//echo 'Se ha creado el directorio: ' . $ruta;
		} /*else {
			echo 'la ruta: ' . $ruta . ' ya existe ';
		}*/
		
		$options = array(
						'upload_dir' => dirname($_SERVER['SCRIPT_FILENAME']).'/assets/melamud/uploads/'. $idPropiedad . '/',
						'upload_url' =>  base_url() .'/assets/melamud/uploads/'. $idPropiedad . '/',
						'image_versions' => array(
										'thumbnail' => array(
											'upload_dir' => dirname($_SERVER['SCRIPT_FILENAME']).'/assets/melamud/uploads/'. $idPropiedad . '/thumbnails/',
											'upload_url' => base_url() .'/assets/melamud/uploads/'. $idPropiedad . '/thumbnails/',
											'max_width' => 80,
											'max_height' => 80
										)
									)
					);
        $upload_handler = new UploadHandler($options);

        header('Pragma: no-cache');
        header('Cache-Control: no-store, no-cache, must-revalidate');
        header('Content-Disposition: inline; filename="files.json"');
        header('X-Content-Type-Options: nosniff');
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: OPTIONS, HEAD, GET, POST, PUT, DELETE');
        header('Access-Control-Allow-Headers: X-File-Name, X-File-Type, X-File-Size');
		
        switch ($_SERVER['REQUEST_METHOD']) {
            case 'OPTIONS':
                break;
            case 'HEAD':
            case 'GET':
                $upload_handler->get();
                break;
            case 'POST':
                if (isset($_REQUEST['_method']) && $_REQUEST['_method'] === 'DELETE') {
                    $upload_handler->delete();
                } else {
                    $upload_handler->post();
                }
                break;
            case 'DELETE':
				$file = explode("/", $_SERVER['PATH_INFO']);;
				//print $file[count($file)-1];
				//print_r($_SERVER['PATH_INFO']);
				
                $upload_handler->delete($file[count($file)-1]);
                break;
            default:
                header('HTTP/1.1 405 Method Not Allowed');
        }

    }
	
	private function cargarCSS()
	{
		$css_files = array();
		$css_files[sha1('/melamud/css/estilos.css')] = base_url() . 'assets/melamud/css/estilos.css';
		$css_files[sha1('/bootstrap/css/bootstrap.css')] = base_url() . 'assets/bootstrap/css/bootstrap.css';
		$css_files[sha1('/flexigrid/css/flexigrid.css')] = base_url() . 'assets/grocery_crud/themes/flexigrid/css/flexigrid.css';
		$css_files[sha1('/melamud/css/jquery.fileupload-ui.css')] = base_url() . 'assets/melamud/css/jquery.fileupload-ui.css';
		$css_files[sha1('/kendo/css/kendo.common.min.css')] = base_url() . 'assets/kendo/css/kendo.common.min.css';
		$css_files[sha1('/kendo/css/kendo.default.min.css')] = base_url() . 'assets/kendo/css/kendo.default.min.css';
		
		
		return $css_files;
	}
	
	private function cargarJS()
	{
		//$js_files[sha1('/grocery_crud/js/jquery-1.8.2.min.js')] = '//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js';
		$js_files[sha1('/kendo/js/jquery.min.js')] = base_url() . 'assets/kendo/js/jquery.min.js';
		$js_files[sha1('/flexigrid/js/jquery.form.js')] = base_url() . 'assets/grocery_crud/themes/flexigrid/js/jquery.form.js';
		$js_files[sha1('/flexigrid/js/flexigrid-add.js')] = base_url() . 'assets/grocery_crud/themes/flexigrid/js/flexigrid-add.js';
		$js_files[sha1('/bootstrap/js/bootstrap.js')] = base_url() . 'assets/bootstrap/js/bootstrap.js';
		
		$js_files[sha1('/melamud/js/address.js')] = base_url() . 'assets/melamud/js/address.js';
		$js_files[sha1('/kendo/js/kendo.web.min.js')] = base_url() . 'assets/kendo/js/kendo.web.min.js';
		
		//$js_files[sha1('/melamud/js/mapa.js')] = base_url() . 'assets/melamud/js/mapa.js';
		$js_files[sha1('/apigoogle')] = 'https://maps.google.com/maps/api/js?sensor=false&libraries=places';
		
		return $js_files;
	}
	
	private function cargarData()
	{
		$idTipoPropiedad 	= $this->input->post('idTipoPropiedad');
		$subtitulo    		= $this->input->post('subtitulo');
		$idLocalidad    	= $this->input->post('idLocalidad');
		$idBarrio    		= $this->input->post('idBarrio');
		$aptoProfesional    = $this->input->post('aptoProfesional');
		$idTipoOperacion    = $this->input->post('idTipoOperacion');
		$antiguedad    		= $this->input->post('antiguedad');
		$calle    			= $this->input->post('calle');
		$altura    			= $this->input->post('altura');
		$titulo   			= $this->input->post('titulo'); //$calle . ' ' . $altura;
		$direccion    		= $this->input->post('direccion');
		$mapa_lat    		= $this->input->post('direccion_lat');
		$mapa_lng    		= $this->input->post('direccion_lng');
		$supTotal    		= $this->input->post('superficieTotal');
		$supCubierta 		= $this->input->post('superficieCubierta');
		$precioPeso    		= $this->input->post('precioPeso');
		$precioDolar    	= $this->input->post('precioDolar');
		$cantAmbientes 		= $this->input->post('cantAmbientes');
		$cantDormitorios    = $this->input->post('cantDormitorios');
		$dependencia    	= $this->input->post('dependencia');
		$cantBanios    		= $this->input->post('cantBanios');
		$cantCocheras    	= $this->input->post('cantCocheras');
		$orientacion    	= $this->input->post('orientacion');
		$idEstadoInmueble 	= $this->input->post('idEstadoInmueble');
		$cantPlantas    	= $this->input->post('cantPlantas');
		$entreCalle    		= $this->input->post('entreCalle1');
		$entreCalle2    	= $this->input->post('entreCalle2');
		$fotoPrincipal    	= $this->input->post('fotoPrincipal');
		$fotoPlano    		= $this->input->post('fotoPlano') == '' ? null : $this->input->post('fotoPlano');
		$expensas    		= $this->input->post('expensas');
		$descripcion    	= $this->input->post('descripcion');
		$requisitos    		= $this->input->post('requisitos');
		$etiqueta			=$this->input->post('idEtiqueta');
		$ubicacion			=$this->input->post('ubicacion');
		$cantOficinas		=$this->input->post('cantOficinas');
		
				
		$adicionales = $this->input->post('adicional');
		
		
		
		//die();
		
		$data = array(
				   'titulo' => $titulo,
				   'idTipo' => $idTipoPropiedad,
				   'subtitulo' => $subtitulo,
				   'idLocalidad' => $idLocalidad,
				   'idBarrio' => ($idBarrio == "") ? NULL : $idBarrio,
				   'profesional' => ($aptoProfesional == "") ? NULL : $aptoProfesional,
				   'idTipoOperacion' => ($idTipoOperacion == "") ? NULL : $idTipoOperacion,
				   'antiguedad' => ($antiguedad == "") ? NULL : $antiguedad,
				   'calle' => ($calle == "") ? NULL : $calle,
				   'calleGoogle' => ($direccion== "") ? NULL : $direccion,
				   'mapa_lat' => ($mapa_lat== "") ? NULL : $mapa_lat,
				   'mapa_lng' => ($mapa_lng== "") ? NULL : $mapa_lng,
				   'altura' => ($altura == "") ? NULL : $altura,
				   'superficieTotal' => ($supTotal == "") ? NULL : $supTotal,
				   'superficieCubierta' => ($supCubierta == "") ? NULL : $supCubierta,
				   'precioPeso' => ($precioPeso == "") ? NULL : $precioPeso,
				   'precioDolar' => ($precioDolar == "") ? NULL : $precioDolar,
				   'cantAmbientes' => ($cantAmbientes == "") ? NULL : $cantAmbientes,
				   'cantDormitorios' => ($cantDormitorios == "") ? NULL : $cantDormitorios,
				   'dependencia' => ($dependencia== "") ? NULL : $dependencia,
				   'cantBanios' => ($cantBanios == "") ? NULL : $cantBanios,
				   'cantCocheras' => ($cantCocheras== "") ? NULL : $cantCocheras,
				   'orientacion' => ($orientacion== "") ? NULL : $orientacion,
				   'idEstadoInmueble' => ($idEstadoInmueble== "") ? NULL : $idEstadoInmueble,
				   'cantPlantas' => ($cantPlantas== "") ? NULL : $cantPlantas,
				   'entreCalle1' => ($entreCalle== "") ? NULL : $entreCalle,
				   'entreCalle2' => ($entreCalle2== "") ? NULL : $entreCalle2,
				   'fotoPrincipal' => ($fotoPrincipal== "") ? NULL : $fotoPrincipal,
				   'fotoPlano' => ($fotoPlano== "") ? NULL : $fotoPlano,
				   'expensas' => ($expensas== "") ? NULL : $expensas,
				   'descripcion' => ($descripcion == "") ? NULL : $descripcion,
				   'requisitos' => ($requisitos == "") ? NULL : $requisitos,
				   'imagenEtiqueta' => ($etiqueta == "") ? NULL : $etiqueta,
				   'ubicacion' => ($ubicacion == "") ? NULL : $ubicacion,
				   'cantOficinas' => ($cantOficinas == "") ? NULL : $cantOficinas,
				);
		
		return $data;
	}
}

/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */